package com.idp.common.error;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 异常处理
 * @author king
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

	private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);


	/**
	 * 自定义异常处理
	 * @param request
	 * @param response
	 * @param e
	 * @return
	 */
	@ExceptionHandler(value = SystemException.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public ErrorInfo exceptionHandler(HttpServletRequest request, HttpServletResponse response, SystemException e) {
		log.info("GlobalExceptionHandler - Exception: " + e.getMessage() + ", URL: " + request.getRequestURL().toString());
		ErrorInfo error = new ErrorInfo();
		error.setCode(e.getCode());
		error.setMessage(e.getMessage());
		error.setUrl(request.getRequestURL().toString());

		return error;
	}

	/**
	 * 未知异常处理
	 * @param request
	 * @param response
	 * @param e
	 * @return
	 */
	@ExceptionHandler(value = Exception.class)
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	public ErrorInfo exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
		log.error("GlobalExceptionHandler - Exception: " + e.getMessage() + ", URL: " + request.getRequestURL().toString());
		log.error(e.getMessage(), e);
		ErrorInfo error = new ErrorInfo();
		error.setCode("10001");
		error.setMessage("系统异常：" + e.getMessage());
		error.setUrl(request.getRequestURL().toString());

		return error;
	}

}
